package com.zx.notification.admin.service.impl;

import com.zx.core.page.PageInfo;
import com.zx.core.wrapper.ListWrapper;
import com.zx.core.wrapper.ObjectWrapper;
import com.zx.core.wrapper.PageWrapper;
import com.zx.core.wrapper.ResponseWrapper;
import com.zx.notification.admin.service.IInboxReadRecordsService;
import com.zx.notification.common.dao.InboxReadRecordsMapper;
import com.zx.notification.common.dao.SystemNotificationsMapper;
import com.zx.notification.common.enums.ReadStatusEnum;
import com.zx.notification.common.mapstruct.InboxReadRecordsMapStructMapper;
import com.zx.notification.common.model.InboxReadRecords;
import com.zx.notification.common.model.SystemNotifications;
import com.zx.notification.common.param.InboxReadRecordsParam;
import com.zx.notification.common.vo.InboxReadRecordsVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * description: 站内信阅读记录管理服务实现类 <br>
 * create: 2025-10-20
 * </p>
 *
 * @author zhou  xun
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class InboxReadRecordsServiceImpl implements IInboxReadRecordsService {

    private final InboxReadRecordsMapper inboxReadRecordsMapper;
    private final SystemNotificationsMapper systemNotificationsMapper;
    private final InboxReadRecordsMapStructMapper inboxReadRecordsMapStructMapper;

    @Override
    public PageWrapper<InboxReadRecordsVO> getInboxReadRecordsVOListByPage(InboxReadRecordsParam inboxReadRecordsParam) {
        PageWrapper<InboxReadRecordsVO> result = new PageWrapper<>();
        try {
            PageInfo pageInfo = new PageInfo(inboxReadRecordsParam.getPageNum(), inboxReadRecordsParam.getPageSize());
            inboxReadRecordsParam.setPageNum(pageInfo.getPageNum());
            inboxReadRecordsParam.setPageSize(pageInfo.getPageSize());

            // 查询总数
            Long count = inboxReadRecordsMapper.getInboxReadRecordsListCount(inboxReadRecordsParam.getUserId(),
                    inboxReadRecordsParam.getNotificationId(),
                    inboxReadRecordsParam.getReadStatus());
            if (count > 0) {
                // 分页查询列表
                List<InboxReadRecordsVO> list = inboxReadRecordsMapper.getInboxReadRecordsListByPage(inboxReadRecordsParam.getUserId(),
                        inboxReadRecordsParam.getNotificationId(),
                        inboxReadRecordsParam.getReadStatus(),
                        inboxReadRecordsParam.getPageNum(),
                        inboxReadRecordsParam.getPageSize());

                // 设置阅读状态描述
                list.forEach(vo -> {
                    if (vo.getReadStatus() != null) {
                        ReadStatusEnum statusEnum = ReadStatusEnum.getEnumByCode(vo.getReadStatus());
                        if (statusEnum != null) {
                            vo.setReadStatusDesc(statusEnum.getDesc());
                        }
                    }
                });

                // 设置返回结果
                result.setData(list);
            }
            result.setTotal(count);
            result.setCurrentPageNum(inboxReadRecordsParam.getPageNum());
            result.setTotalPage(pageInfo);
        } catch (Exception e) {
            log.error("获取站内信阅读记录列表时发生错误", e);
            result.fail("获取站内信阅读记录列表失败，请稍后重试");
        }

        return result;
    }

    @Override
    public ListWrapper<InboxReadRecordsVO> getInboxReadRecordsListByUserIdAndStatus(String userId, String readStatus) {
        ListWrapper<InboxReadRecordsVO> result = new ListWrapper<>();
        try {
            // 查询列表
            List<InboxReadRecordsVO> list = inboxReadRecordsMapper.selectByUserIdAndReadStatus(userId, readStatus);

            // 设置阅读状态描述
            list.forEach(vo -> {
                if (vo.getReadStatus() != null) {
                    ReadStatusEnum statusEnum = ReadStatusEnum.getEnumByCode(vo.getReadStatus());
                    if (statusEnum != null) {
                        vo.setReadStatusDesc(statusEnum.getDesc());
                    }
                }
            });

            // 设置返回结果
            result.setData(list);
        } catch (Exception e) {
            log.error("根据用户ID和阅读状态查询站内信阅读记录列表时发生错误", e);
            result.fail("查询站内信阅读记录列表失败，请稍后重试");
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper updateReadStatus(String notificationId, String readStatus) {
        ResponseWrapper result = new ResponseWrapper();
        try {
            if (readStatus != null) {
                // 验证阅读状态是否有效
                ReadStatusEnum enumByCode = ReadStatusEnum.getEnumByCode(readStatus);
                if (enumByCode == null) {
                    result.fail("阅读状态不正确");
                    return result;
                }
            }

            // 验证要更新的数据是否存在
            List<InboxReadRecords> existingRecords = inboxReadRecordsMapper.selectByNotificationId(notificationId);
            if (existingRecords.isEmpty()) {
                result.fail("未找到对应的站内信阅读记录");
                return result;
            }

            // 更新阅读状态
            InboxReadRecords recordToUpdate = new InboxReadRecords();
            // 设置ID以确保更新操作能正确执行
            recordToUpdate.setId(existingRecords.get(0).getId());
            recordToUpdate.setNotificationId(notificationId);
            recordToUpdate.setReadStatus(readStatus);
            recordToUpdate.setReadTime(LocalDateTime.now());
            recordToUpdate.setUpdateTime(LocalDateTime.now());
            inboxReadRecordsMapper.updateByPrimaryKeySelective(recordToUpdate);
        } catch (Exception e) {
            log.error("更新阅读状态时发生错误", e);
            result.fail("更新阅读状态失败: " + e.getMessage());
            // 重新抛出异常以触发事务回滚
            throw e;
        }

        return result;
    }

    @Override
    public ObjectWrapper<InboxReadRecordsVO> selectInboxReadRecordById(String inboxReadRecordId) {
        ObjectWrapper<InboxReadRecordsVO> result = new ObjectWrapper<>();
        try {
            // 验证站内信阅读记录是否存在
            InboxReadRecords selectByPrimaryKey = inboxReadRecordsMapper.selectByPrimaryKey(inboxReadRecordId);
            if (null == selectByPrimaryKey) {
                result.fail("站内信阅读记录不存在");
                return result;
            }

            InboxReadRecordsVO inboxReadRecordsVO = inboxReadRecordsMapStructMapper.inboxReadRecordsToInboxReadRecordsVO(selectByPrimaryKey);

            // 查询关联的通知信息以获取标题和内容
            if (selectByPrimaryKey.getNotificationId() != null) {
                SystemNotifications notification = systemNotificationsMapper.selectByPrimaryKey(selectByPrimaryKey.getNotificationId());
                if (notification != null) {
                    // 手动设置通知标题和内容
                    inboxReadRecordsVO.setTitle(notification.getTitle());
                    inboxReadRecordsVO.setContent(notification.getContent());
                }
            }

            result.setData(inboxReadRecordsVO);
        } catch (Exception e) {
            log.error("获取站内信阅读记录信息时发生错误", e);
            result.fail("获取站内信阅读记录信息失败，请稍后重试");
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper deleteInboxReadRecordById(String inboxReadRecordId) {
        ResponseWrapper result = new ResponseWrapper();

        try {
            // 验证站内信阅读记录是否存在
            InboxReadRecords existingInboxReadRecord = inboxReadRecordsMapper.selectByPrimaryKey(inboxReadRecordId);
            if (null == existingInboxReadRecord) {
                result.fail("站内信阅读记录不存在");
                return result;
            }

            // 删除站内信阅读记录
            inboxReadRecordsMapper.deleteByPrimaryKey(inboxReadRecordId);
        } catch (Exception e) {
            log.error("删除站内信阅读记录时发生系统错误", e);
            result.fail("删除站内信阅读记录失败: " + e.getMessage());
            // 重新抛出异常以触发事务回滚
            throw e;
        }
        return result;
    }
}